﻿namespace Zhaoxi.ReadingPlatform.WebSiteApi.Utility.Middleware
{
    public class DownloadImagesMiddleware
    {
        private string _directoryPath;
        private RequestDelegate _next;

        public DownloadImagesMiddleware(RequestDelegate next, string path)
        {
            _next = next;
            _directoryPath = path;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            if (context.Request.Path.Value!.EndsWith(".jpg"))// 规则需要自定义
            {
                string fileUrl = $"{Directory.GetCurrentDirectory()}\\{_directoryPath}{context.Request.Path.Value}";

                if (!File.Exists(fileUrl))// 如果文件不存在就继续往后走
                {
                    await _next(context);// 啥也不干
                    return;
                }

                #region 传送文件
                {
                    context.Request.EnableBuffering();
                    context.Request.Body.Position = 0;
                    var responseStream = context.Response.Body;
                    using (FileStream newStream = new FileStream(fileUrl, FileMode.Open))
                    {
                        context.Response.Body = newStream;
                        newStream.Position = 0;
                        var responseReader = new StreamReader(newStream);
                        var responseContent = await responseReader.ReadToEndAsync();
                        newStream.Position = 0;
                        await newStream.CopyToAsync(responseStream);
                        context.Response.Body = responseStream;
                    }
                }
                #endregion
            }
            else
            {
                await _next(context);
            }
        }
    }
}
